<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElHeader, ElMain, ElAlert } from 'element-plus'

const router = useRouter()
const route = useRoute()
const message = ref('')

// 检查用户是否已认证
const isAuthenticated = () => {
  // 检查本地存储中的认证状态和token
  const authStatus = localStorage.getItem('isAuthenticated') === 'true'
  const token = localStorage.getItem('token')
  
  // 如果有认证状态但没有token，或者有token但没有认证状态，则清理认证信息
  if ((authStatus && !token) || (token && !authStatus)) {
    localStorage.removeItem('isAuthenticated')
    localStorage.removeItem('token')
    return false
  }
  
  return authStatus && token
}

// 退出登录
const logout = () => {
  localStorage.removeItem('isAuthenticated')
  localStorage.removeItem('token')
  localStorage.removeItem('savedUsername')
  ElMessage.success('已退出登录')
  router.push('/login')
}

// 页面加载时检查认证状态
onMounted(() => {
  // 如果用户未认证且不在登录页面，则重定向到登录页面
  if (!isAuthenticated() && route.path !== '/login') {
    router.push('/login')
  }
})
</script>

<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <el-header class="app-header">
      <div class="header-content">
        <h1 class="app-title">ProbeNice医学影像系统</h1>
        <div class="user-actions" v-if="isAuthenticated() && route.path !== '/login'">
          <el-button @click="logout" type="danger" plain>退出登录</el-button>
        </div>
      </div>
    </el-header>
    
    <!-- 主内容区域 -->
    <el-main class="app-main">
      <router-view />
    </el-main>
    
    <!-- 消息提示 -->
    <div v-if="message" class="global-message">
      <el-alert
        :title="message"
        type="success"
        :closable="false"
      />
    </div>
  </div>
</template>

<style scoped>
.app-container { 
  background-color: #f5f5f5;
}

.app-header {
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
}

.app-title {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-style: italic;
  color: #ff69b4;
  font-family: 'Times New Roman', Times, serif;
}

.app-main { 
  padding: 1px;
}

.global-message {
  position: fixed;
  top: 70px;
  right: 20px;
  z-index: 1000;
}
</style>
